<!-- build time:Tue Dec 17 2019 19:26:42 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Spring,Spring Boot,WebFlux,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="Spring MVC Web架构是基于阻塞式Servlet API构建的。Servlet 3.1后提供了非阻塞API，Spring 5.0后基于这些API构建了一套全新的非阻塞Web框架 —— WebFlux。Spring Boot 2.0基于Spring 5.0构建，所以要在Spring Boot中使用WebFlux架构，版本必须大于2.0。通过下面这张图了解下Spring MVC和Spring"><meta name="keywords" content="Spring,Spring Boot,WebFlux"><meta property="og:type" content="article"><meta property="og:title" content="Spring Boot 2.0 WebFlux编程"><meta property="og:url" content="http://mrbird.cc/Spring-Boot-2-0-WebFlux.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="Spring MVC Web架构是基于阻塞式Servlet API构建的。Servlet 3.1后提供了非阻塞API，Spring 5.0后基于这些API构建了一套全新的非阻塞Web框架 —— WebFlux。Spring Boot 2.0基于Spring 5.0构建，所以要在Spring Boot中使用WebFlux架构，版本必须大于2.0。通过下面这张图了解下Spring MVC和Spring"><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/diagram-boot-reactor.svg"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401110755.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401113446.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401134616.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401135918.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401140024.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401140239.png"><meta property="og:image" content="http://mrbird.cc/img/flux.gif"><meta property="og:image" content="http://mrbird.cc/img/asfasfdvvasd.gif"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401170048.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401170950.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190401173002.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190402090631.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190402092516.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190402092833.png"><meta property="og:updated_time" content="2019-10-28T12:14:46.268Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Spring Boot 2.0 WebFlux编程"><meta name="twitter:description" content="Spring MVC Web架构是基于阻塞式Servlet API构建的。Servlet 3.1后提供了非阻塞API，Spring 5.0后基于这些API构建了一套全新的非阻塞Web框架 —— WebFlux。Spring Boot 2.0基于Spring 5.0构建，所以要在Spring Boot中使用WebFlux架构，版本必须大于2.0。通过下面这张图了解下Spring MVC和Spring"><meta name="twitter:image" content="http://mrbird.cc/img/diagram-boot-reactor.svg"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>Spring Boot 2.0 WebFlux编程 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Spring-Boot-2-0-WebFlux.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Spring Boot 2.0 WebFlux编程</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-19T15:25:54+08:00">2018-11-19 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>Spring MVC Web架构是基于阻塞式Servlet API构建的。Servlet 3.1后提供了非阻塞API，Spring 5.0后基于这些API构建了一套全新的非阻塞Web框架 —— WebFlux。Spring Boot 2.0基于Spring 5.0构建，所以要在Spring Boot中使用WebFlux架构，版本必须大于2.0。</p><p>通过下面这张图了解下Spring MVC和Spring WebFlux的区别：<a id="more"></a></p><p><img src="img/diagram-boot-reactor.svg" style="width:35rem"> <a href="img/https://www.cnblogs.com/javabg/p/7976977.html">https://www.cnblogs.com/javabg/p/7976977.html</a></p><p>可以看到，Spring WebFlux是非阻塞式的，支持 Reactive Streams背压，并在Netty，Undertow和Servlet 3.1+容器等服务器上运行。其目前只支持非关系型数据库，如Mongo，Redis等。非阻塞式的编程模型可以提高程序的并发量，提升性能和吞吐量。</p><h2 id="异步Servlet"><a href="#异步Servlet" class="headerlink" title="异步Servlet"></a>异步Servlet</h2><p>既然WebFlux是基于异步Servelt API构建的，那么我们先来看看什么是异步Servlet。</p><p>使用IDEA创建一个传统的Java Web应用（可以参考<a href="https://www.cnblogs.com/javabg/p/7976977.html" target="_blank" rel="noopener">https://www.cnblogs.com/javabg/p/7976977.html</a>），然后创建一个<code>SyncServlet</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@WebServlet</span>(urlPatterns = <span class="string">"/sync"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SyncServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">7583536145022393360L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Logger log = Logger.getLogger(SyncServlet.class.getName());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">this</span>.execute(request, response);</span><br><span class="line">        log.info(<span class="string">"总耗时："</span> + (System.currentTimeMillis() - start) + <span class="string">"ms"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">2</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            response.getWriter().append(<span class="string">"hello"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>doGet</code>方法中线程阻塞2秒，然后打印hello。部署项目到Tomcat，context-path为/servlet，启动后访问<a href="http://localhost:8080/servlet/sync" target="_blank" rel="noopener">http://localhost:8080/servlet/sync</a>:</p><p><img src="img/QQ截图20190401110755.png" alt="QQ截图20190401110755.png"></p><p>传统的Servlet API是阻塞的，<code>log.info(&quot;总耗时：&quot; + (System.currentTimeMillis() - start) + &quot;ms&quot;)</code>这行代码必须等待<code>this.execute()</code>执行完毕后才开始执行。</p><p>接下来看看非阻塞Servlet API是怎么搞的。新建一个<code>AsyncServlet</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@WebServlet</span>(urlPatterns = <span class="string">"/async"</span>, asyncSupported = <span class="keyword">true</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">393375716683413545L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Logger log = Logger.getLogger(AsyncServlet.class.getName());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        AsyncContext asyncContext = request.startAsync();</span><br><span class="line"></span><br><span class="line">        CompletableFuture.runAsync(() -&gt; execute(</span><br><span class="line">            asyncContext, </span><br><span class="line">            asyncContext.getRequest(), </span><br><span class="line">            asyncContext.getResponse())</span><br><span class="line">        );</span><br><span class="line">        log.info(<span class="string">"总耗时："</span> + (System.currentTimeMillis() - start) + <span class="string">"ms"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(AsyncContext asyncContext, ServletRequest request, ServletResponse response)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">2</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            response.getWriter().append(<span class="string">"hello"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        asyncContext.complete();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>在类上使用<code>@WebServlet(asyncSupported = true)</code>开启异步支持，通过<code>AsyncContext asyncContext = request.startAsync();</code>获取异步上下文<code>AsyncContext</code>，<code>AsyncContext</code>的<code>complete</code>方法用于标识异步调用结束。<code>CompletableFuture</code>为Java 8提供的<code>Future</code>接口实现类，可以方便的处理异步调用。</p><p>启动项目，访问<a href="http://localhost:8080/servlet/async" target="_blank" rel="noopener">http://localhost:8080/servlet/async</a>，响应耗时也在2秒左右，但是这个过程是异步的，查看控制台日志就可以证明这点：</p><p><img src="img/QQ截图20190401113446.png" alt="QQ截图20190401113446.png"></p><p>所以，异步调用适用于那些对方法返回值没有影响的操作，比如异步记录用户操作日志等。如果方法的返回值依赖于异步调用的结果，那么方法耗时在同步和异步上是没有区别的。</p><h2 id="Mono和Flux"><a href="#Mono和Flux" class="headerlink" title="Mono和Flux"></a>Mono和Flux</h2><p>了解了异步Servlet后，我们回到WebFlux，新建一个SpringBoot程序，版本为2.1.3.RELEASE，并引入<code>spring-boot-starter-webflux</code>依赖：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-webflux<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p><a href="https://github.com/reactor/reactor" target="_blank" rel="noopener">Reactor</a> 是Spring WebFlux所使用的响应式库，其提供了两个特殊的类Mono和Flux。</p><p>Mono和Flux在发布订阅模式中都属于发布者（不清楚的可以参考<a href="/Java-9-Flow-API-Learn.html">Java 9 Flow API学习</a>），查看源码会发现它们都实现了Publisher接口。</p><p>Mono表示0 ~ 1个元素的数据发布者，Flux表示 0 ~ N个元素的数据发布者。我们可以通过一个例子来了解Mono和Flux，创建<code>MonoFluxTest</code>类：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MonoFluxTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Subscriber&lt;Integer&gt; subscriber = <span class="keyword">new</span> Subscriber&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="keyword">private</span> Subscription subscription;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onSubscribe</span><span class="params">(Subscription subscription)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">this</span>.subscription = subscription;</span><br><span class="line">                <span class="keyword">this</span>.subscription.request(<span class="number">1</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(Integer item)</span> </span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"接受到数据: "</span> + item);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    TimeUnit.SECONDS.sleep(<span class="number">3</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">this</span>.subscription.request(<span class="number">1</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable throwable)</span> </span>&#123;</span><br><span class="line">                throwable.printStackTrace();</span><br><span class="line">                <span class="keyword">this</span>.subscription.cancel();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onComplete</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"处理完了!"</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;;</span><br><span class="line">        </span><br><span class="line">        String[] strs = &#123;<span class="string">"1"</span>, <span class="string">"2"</span>, <span class="string">"3"</span>&#125;;</span><br><span class="line">        Flux.fromArray(strs).map(Integer::parseInt).subscribe(subscriber);</span><br><span class="line">        Mono.fromSupplier(() -&gt; <span class="number">1</span>).map(s -&gt; s + <span class="number">1</span>).subscribe(subscriber);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>程序首先创建了一个订阅者（参考<a href="/Java-9-Flow-API-Learn.html">Java 9 Flow API学习</a>），然后分别使用<code>Flux.fromArray</code>和<code>Mono.fromSupplier</code>构造了<code>Flux</code>类型发布者和<code>Mono</code>类型发布者，并和订阅者保持订阅关系。</p><p>运行main方法，控制台输出：</p><p><img src="img/QQ截图20190401134616.png" alt="QQ截图20190401134616.png"></p><p>了解了Mono和Flux后，我们新建一个TestController：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestController</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"sync"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sync</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"sync method start"</span>);</span><br><span class="line">        String result = <span class="keyword">this</span>.execute();</span><br><span class="line">        logger.info(<span class="string">"sync method end"</span>);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"async/mono"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Mono&lt;String&gt; <span class="title">asyncMono</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"async method start"</span>);</span><br><span class="line">        Mono&lt;String&gt; result = Mono.fromSupplier(<span class="keyword">this</span>::execute);</span><br><span class="line">        logger.info(<span class="string">"async method end"</span>);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> String <span class="title">execute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">2</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"hello"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>execute</code>方法返回一个值hello，所以可以使用Mono来处理返回值，使它成为一个异步方法。<code>asyncMono</code>方法返回<code>Mono&lt;String&gt;</code>类型，也就是一个String类型的数据发布者，我们不用去手动处理订阅关系，Spring会帮我们处理，我们直接返回即可。</p><p>启动项目，可以看到WebFlux默认使用的是Netty服务器：</p><p><img src="img/QQ截图20190401135918.png" alt="QQ截图20190401135918.png"></p><p>分别访问<a href="http://localhost:8080/sync" target="_blank" rel="noopener">http://localhost:8080/sync</a>和<a href="http://localhost:8080/async/mono" target="_blank" rel="noopener">http://localhost:8080/async/mono</a>，控制台输出如下：</p><p><img src="img/QQ截图20190401140024.png" alt="QQ截图20190401140024.png"></p><p><img src="img/QQ截图20190401140239.png" alt="QQ截图20190401140239.png"></p><p>可以看到<code>asyncMono</code>方法里的<code>Mono&lt;String&gt; result = Mono.fromSupplier(this::execute)</code>是异步非阻塞的，并且<a href="http://localhost:8080/async/mono" target="_blank" rel="noopener">http://localhost:8080/async/mono</a>返回的值为字符串hello。</p><p>下面我们来看一个返回类型为<code>Flux&lt;String&gt;</code>类型的例子。</p><h2 id="Server-Sent-Events"><a href="#Server-Sent-Events" class="headerlink" title="Server Sent Events"></a>Server Sent Events</h2><p>返回值类型为<code>Flux</code>的时候，它是一个数据流，不是一次性数据包，服务端会不断地（假如Flux数据长度大于1）往客户端发送数据。这时，客户端不会关闭连接，会一直等着服务器发过来的新的数据流。这种模式称为Server-Sent Events。</p><p>在TestController新增一个<code>asyncFlux</code>方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping</span>(value = <span class="string">"async/flux"</span>, produces = MediaType.TEXT_EVENT_STREAM_VALUE)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Flux&lt;String&gt; <span class="title">asyncFlux</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    logger.info(<span class="string">"async method start"</span>);</span><br><span class="line">    Flux&lt;String&gt; result = Flux.fromStream(IntStream.range(<span class="number">1</span>, <span class="number">5</span>).mapToObj(i -&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"int value："</span> + i;</span><br><span class="line">    &#125;));</span><br><span class="line">    logger.info(<span class="string">"async method end"</span>);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>@GetMapping</code>必须通过<code>produces</code>指定数据类型为<code>text/event-stream</code>，重启项目，访问<a href="http://localhost:8080/async/flux" target="_blank" rel="noopener">http://localhost:8080/async/flux</a>：</p><p><img src="img/flux.gif" alt="flux.gif"></p><p>前端可以通过H5的<code>EventSource</code>来接收。</p><p>引入thymeleaf依赖：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-thymeleaf<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>然后在resources/templates下新建flux.html：</p><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>test sse<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> es = <span class="keyword">new</span> EventSource(<span class="string">"async/flux"</span>);</span></span><br><span class="line"><span class="javascript">    es.onmessage = <span class="function"><span class="keyword">function</span> (<span class="params">evt</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(evt.data);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">if</span> (evt.data === <span class="string">"int value：4"</span>) &#123;</span></span><br><span class="line"><span class="undefined">            es.close();</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">    &#125;;</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>需要调用<code>es.close()</code>来关闭事件流，不然<code>EventSource</code>会在数据传输完毕会自动重连，这样就会不间断的调用<code>localhost:8080/async/flux</code>请求了。</p><p>添加一个ViewController，用来访问flux.html：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ViewController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"flux"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">flux</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"flux"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>重启项目，访问<a href="http://localhost:8080/flux" target="_blank" rel="noopener">http://localhost:8080/flux</a>，浏览器控制台输出如下所示:</p><p><img src="img/asfasfdvvasd.gif" alt="asfasfdvvasd.gif"></p><h2 id="Mono-Flux常用方法"><a href="#Mono-Flux常用方法" class="headerlink" title="Mono,Flux常用方法"></a>Mono,Flux常用方法</h2><p>通过上面的例子，我们简单了解了Mono和Flux的用法和区别，下面我们列举一些它们的常用方法。</p><h3 id="源头操作"><a href="#源头操作" class="headerlink" title="源头操作"></a>源头操作</h3><p><strong>Flux</strong></p><p>可以通过Flux类的静态方法来生成：</p><ol><li><p><code>just()</code>：可以指定序列中包含的全部元素。创建出来的 Flux 序列在发布这些元素之后会自动结束。</p></li><li><p><code>fromArray()</code>，<code>fromIterable()</code>和 <code>fromStream()</code>：可以从一个数组、Iterable 对象或 Stream 对象中创建 Flux 对象。</p></li><li><p><code>empty()</code>：创建一个不包含任何元素，只发布结束消息的序列。</p></li><li><p><code>error(Throwable error)</code>：创建一个只包含错误消息的序列。</p></li><li><p><code>never()</code>：创建一个不包含任何消息通知的序列。</p></li><li><p><code>range(int start, int count)</code>：创建包含从 start 起始的 count 个数量的 Integer 对象的序列。</p></li><li><p><code>interval(Duration period)</code>和 <code>interval(Duration delay, Duration period)</code>：创建一个包含了从 0 开始递增的 Long 对象的序列。其中包含的元素按照指定的间隔来发布。除了间隔时间之外，还可以指定起始元素发布之前的延迟时间。</p></li></ol><p>举些例子：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    Flux.just(<span class="string">"Hello"</span>, <span class="string">"World"</span>).subscribe(System.out::println);</span><br><span class="line">    Flux.fromArray(<span class="keyword">new</span> Integer[] &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;).subscribe(System.out::println);</span><br><span class="line">    Flux.empty().subscribe(System.out::println);</span><br><span class="line">    Flux.range(<span class="number">1</span>, <span class="number">4</span>).subscribe(System.out::println);</span><br><span class="line">    Flux.interval(Duration.of(<span class="number">1</span>, ChronoUnit.SECONDS)).subscribe(System.out::println);</span><br><span class="line">    <span class="comment">// 线程延迟关闭，不然最后一个例子木有输出</span></span><br><span class="line">    Thread.currentThread().join(<span class="number">10000</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>输出如下所示： <img src="img/QQ截图20190401170048.png" alt="QQ截图20190401170048.png"></p><p>上面的这些静态方法适合于简单的Flux序列生成，当序列的生成需要复杂的逻辑时，则应该使用<code>generate()</code>或<code>create()</code>方法。</p><p><strong>generate()</strong></p><p>generate()方法通过同步和逐一的方式来产生 Flux 序列。序列的产生是通过调用所提供的 SynchronousSink 对象的 next()，complete()和 error(Throwable)方法来完成的：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Flux.generate(sink -&gt; &#123;</span><br><span class="line">    sink.next(<span class="string">"Hello"</span>);</span><br><span class="line">    sink.complete();</span><br><span class="line">&#125;).subscribe(System.out::println);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">final</span> Random random = <span class="keyword">new</span> Random();</span><br><span class="line">Flux.generate(ArrayList::<span class="keyword">new</span>, (list, sink) -&gt; &#123;</span><br><span class="line">    <span class="keyword">int</span> value = random.nextInt(<span class="number">100</span>);</span><br><span class="line">    list.add(value);</span><br><span class="line">    sink.next(value);</span><br><span class="line">    <span class="keyword">if</span> (list.size() == <span class="number">10</span>) &#123;</span><br><span class="line">        sink.complete();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> list;</span><br><span class="line">&#125;).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出如下所示:</p><p><img src="img/QQ截图20190401170950.png" alt="QQ截图20190401170950.png"></p><p>如果不调用 complete()方法，所产生的是一个无限序列。</p><p><strong>create()</strong></p><p>create()方法与 generate()方法的不同之处在于所使用的是 FluxSink 对象。FluxSink 支持同步和异步的消息产生，并且可以在一次调用中产生多个元素：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Flux.create(sink -&gt; &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">        sink.next(i);</span><br><span class="line">    &#125;</span><br><span class="line">    sink.complete();</span><br><span class="line">&#125;).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p><strong>Mono</strong></p><p>Mono 的创建方式与之前介绍的 Flux 比较相似。Mono 类中也包含了一些与 Flux 类中相同的静态方法。这些方法包括 just()，empty()，error()和 never()等。除了这些方法之外，Mono 还有一些独有的静态方法：</p><ol><li><p><code>fromCallable()</code>、<code>fromCompletionStage()</code>、<code>fromFuture()</code>、<code>fromRunnable(</code>)和 <code>fromSupplier()</code>：分别从 Callable、CompletionStage、CompletableFuture、Runnable 和 Supplier 中创建 Mono。</p></li><li><p><code>delay(Duration duration)</code>：创建一个 Mono 序列，在指定的延迟时间之后，产生数字 0 作为唯一值。</p></li><li><p><code>ignoreElements(Publisher&lt;T&gt; source)</code>：创建一个 Mono 序列，忽略作为源的 Publisher 中的所有元素，只产生结束消息。</p></li><li><p><code>justOrEmpty(Optional&lt;? extends T&gt; data)</code>和 <code>justOrEmpty(T data)</code>：从一个 Optional 对象或可能为 null 的对象中创建 Mono。只有 Optional 对象中包含值或对象不为 null 时，Mono 序列才产生对应的元素。</p></li></ol><p>举些例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Mono.just(<span class="string">"are"</span>).subscribe(System.out::println);</span><br><span class="line">Mono.empty().subscribe(System.out::println);</span><br><span class="line">Mono.fromSupplier(() -&gt; <span class="string">"you"</span>).subscribe(System.out::println);</span><br><span class="line">Mono.justOrEmpty(Optional.of(<span class="string">"ok"</span>)).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出:</p><p><img src="img/QQ截图20190401173002.png" alt="QQ截图20190401173002.png"></p><p>还可以通过 create()方法来使用 MonoSink 来创建 Mono：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Mono.create(sink -&gt; sink.success(<span class="string">"Hello"</span>)).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><h3 id="中间操作"><a href="#中间操作" class="headerlink" title="中间操作"></a>中间操作</h3><p><strong>filter</strong></p><p>对流中包含的元素进行过滤，只留下满足 Predicate 指定条件的元素：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Flux.range(<span class="number">1</span>, <span class="number">10</span>).filter(i -&gt; i % <span class="number">2</span> == <span class="number">0</span>).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出前10偶数。</p><p><strong>take</strong></p><p>take 系列操作符用来从当前流中提取元素。提取的方式可以有很多种。</p><ol><li><p><code>take(long n)</code>：按照指定的数量来提取。</p></li><li><p><code>takeLast(long n)</code>：提取流中的最后 N 个元素。</p></li><li><p><code>takeUntil(Predicate&lt;? super T&gt; predicate)</code>：提取元素直到 Predicate 返回 true。</p></li></ol><p>4 <code>takeWhile(Predicate&lt;? super T&gt; continuePredicate)</code>： 当 Predicate 返回 true 时才进行提取。</p><p>举些例子：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Flux.range(<span class="number">1</span>, <span class="number">20</span>).take(<span class="number">10</span>).subscribe(System.out::println);</span><br><span class="line">Flux.range(<span class="number">1</span>, <span class="number">20</span>).takeLast(<span class="number">10</span>).subscribe(System.out::println);</span><br><span class="line">Flux.range(<span class="number">1</span>, <span class="number">20</span>).takeWhile(i -&gt; i &lt; <span class="number">10</span>).subscribe(System.out::println);</span><br><span class="line">Flux.range(<span class="number">1</span>, <span class="number">20</span>).takeUntil(i -&gt; i == <span class="number">10</span>).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p><strong>reduce 和 reduceWith</strong></p><p>reduce 和 reduceWith 操作符对流中包含的所有元素进行累积操作，得到一个包含计算结果的 Mono 序列。累积操作是通过一个 BiFunction 来表示的。在操作时可以指定一个初始值。如果没有初始值，则序列的第一个元素作为初始值。</p><p>比如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Flux.range(<span class="number">1</span>, <span class="number">10</span>).reduce((x, y) -&gt; x + y).subscribe(System.out::println);</span><br><span class="line">Flux.range(<span class="number">1</span>, <span class="number">10</span>).reduceWith(() -&gt; <span class="number">10</span>, (x, y) -&gt; x + y).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>第一行语句对流中的元素进行相加操作，结果为 55；第二行语句同样也是进行相加操作，不过通过一个 Supplier 给出了初始值为 10，所以结果为 65。</p><p><strong>merge</strong></p><p><code>merge</code>操作符用来把多个流合并成一个 Flux 序列：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Flux.merge(</span><br><span class="line">        Flux.interval(Duration.of(<span class="number">500</span>, ChronoUnit.MILLIS)).take(<span class="number">2</span>),</span><br><span class="line">        Flux.interval(Duration.of(<span class="number">500</span>, ChronoUnit.MILLIS)).take(<span class="number">2</span>)</span><br><span class="line">).toStream().forEach(System.out::println);</span><br></pre></td></tr></table></figure><p>输出 0 0 1 1。</p><p><strong>buffer</strong></p><p>直接看例子吧：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Flux.range(<span class="number">1</span>, <span class="number">100</span>).buffer(<span class="number">20</span>).subscribe(System.out::println);</span><br><span class="line">Flux.range(<span class="number">1</span>, <span class="number">10</span>).bufferUntil(i -&gt; i % <span class="number">2</span> == <span class="number">0</span>).subscribe(System.out::println);</span><br><span class="line">Flux.range(<span class="number">1</span>, <span class="number">10</span>).bufferWhile(i -&gt; i % <span class="number">2</span> == <span class="number">0</span>).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出如下所示：</p><p><img src="img/QQ截图20190402090631.png" alt="QQ截图20190402090631.png"></p><p>类似于数据流分区。</p><p><strong>zipWith</strong></p><p>将两个流的元素安装元素位置一一组合：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Flux.just(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>)</span><br><span class="line">    .zipWith(Flux.just(<span class="string">"e"</span>, <span class="string">"f"</span>, <span class="string">"g"</span>, <span class="string">"h"</span>, <span class="string">"i"</span>))</span><br><span class="line">    .subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出：</p><p><img src="img/QQ截图20190402092516.png" alt="QQ截图20190402092516.png"></p><p>没有配对上的被丢弃。</p><p>另外一个例子：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Flux.just(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>)</span><br><span class="line">    .zipWith(Flux.just(<span class="string">"e"</span>, <span class="string">"f"</span>, <span class="string">"g"</span>, <span class="string">"h"</span>, <span class="string">"i"</span>), (s1, s2) -&gt; String.format(<span class="string">"%s-%s"</span>, s1, s2))</span><br><span class="line">    .subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出如下:</p><p><img src="img/QQ截图20190402092833.png" alt="QQ截图20190402092833.png"></p><p><strong>flatMap</strong></p><p>把流中的每个元素转换成一个流，再把所有流中的元素进行合并。</p><p>比如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Flux.just(<span class="number">5</span>, <span class="number">10</span>).flatMap(</span><br><span class="line">            x -&gt; Flux.range(<span class="number">1</span>, x).take(x)</span><br><span class="line">    ).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><h3 id="终端处理"><a href="#终端处理" class="headerlink" title="终端处理"></a>终端处理</h3><p>通过<code>subscribe()</code>方法处理正常和错误消息：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Flux.just(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">    .concatWith(Mono.error(<span class="keyword">new</span> IllegalStateException()))</span><br><span class="line">    .subscribe(System.out::println, System.err::println);</span><br></pre></td></tr></table></figure><p></p><p>输出:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">java.lang.IllegalStateException</span><br></pre></td></tr></table></figure><p></p><p>出现错误时返回默认值：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Flux.just(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">    .concatWith(Mono.error(<span class="keyword">new</span> IllegalStateException()))</span><br><span class="line">    .onErrorReturn(<span class="number">0</span>)</span><br><span class="line">    .subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出：</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">0</span><br></pre></td></tr></table></figure><p></p><p>出现错误时使用另外的流：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Flux.just(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">    .concatWith(Mono.error(<span class="keyword">new</span> IllegalArgumentException()))</span><br><span class="line">    .onErrorResume(e -&gt; &#123;</span><br><span class="line">        <span class="keyword">if</span> (e <span class="keyword">instanceof</span> IllegalStateException) &#123;</span><br><span class="line">            <span class="keyword">return</span> Mono.just(<span class="number">0</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> IllegalArgumentException) &#123;</span><br><span class="line">            <span class="keyword">return</span> Mono.just(-<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> Mono.empty();</span><br><span class="line">    &#125;).subscribe(System.out::println);</span><br></pre></td></tr></table></figure><p></p><p>输出如下:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">-1</span><br></pre></td></tr></table></figure><p></p><p>源码链接：<a href="https://github.com/wuyouzhuguli/SpringAll/tree/master/57.Spring-Boot-WebFlux" target="_blank" rel="noopener">https://github.com/wuyouzhuguli/SpringAll/tree/master/57.Spring-Boot-WebFlux</a></p><p>参考链接:</p><ol><li><p><a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-webflux" target="_blank" rel="noopener">https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-webflux</a></p></li><li><p><a href="https://developer.mozilla.org/zh-CN/docs/Server-sent_events/Using_server-sent_events" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Server-sent_events/Using_server-sent_events</a></p></li><li><p><a href="http://www.ruanyifeng.com/blog/2017/05/server-sent_events.html" target="_blank" rel="noopener">http://www.ruanyifeng.com/blog/2017/05/server-sent_events.html</a></p></li><li><p><a href="https://projectreactor.io/docs/core/release/reference/#flux" target="_blank" rel="noopener">https://projectreactor.io/docs/core/release/reference/#flux</a></p></li><li><p><a href="https://www.ibm.com/developerworks/cn/java/j-cn-with-reactor-response-encode/index.html" target="_blank" rel="noopener">https://www.ibm.com/developerworks/cn/java/j-cn-with-reactor-response-encode/index.html</a></p></li></ol><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Spring-Boot-2-0-WebFlux.html" title="Spring Boot 2.0 WebFlux编程">http://mrbird.cc/Spring-Boot-2-0-WebFlux.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Spring/" rel="tag"># Spring</a> <a href="/tags/Spring-Boot/" rel="tag"># Spring Boot</a> <a href="/tags/WebFlux/" rel="tag"># WebFlux</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Spring-Boot-Mongo-DB-CRUD.html" rel="next" title="Spring Boot整合Mongo DB"><i class="fa fa-chevron-left"></i> Spring Boot整合Mongo DB</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Spring-Boot-Kafka.html" rel="prev" title="Spring Boot整合Kafka">Spring Boot整合Kafka <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#异步Servlet"><span class="nav-number">1.</span> <span class="nav-text">异步Servlet</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Mono和Flux"><span class="nav-number">2.</span> <span class="nav-text">Mono和Flux</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Server-Sent-Events"><span class="nav-number">3.</span> <span class="nav-text">Server Sent Events</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Mono-Flux常用方法"><span class="nav-number">4.</span> <span class="nav-text">Mono,Flux常用方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#源头操作"><span class="nav-number">4.1.</span> <span class="nav-text">源头操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#中间操作"><span class="nav-number">4.2.</span> <span class="nav-text">中间操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#终端处理"><span class="nav-number">4.3.</span> <span class="nav-text">终端处理</span></a></li></ol></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->